package com.example.ribbon.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.auth.domain.DataNode;
import com.example.config.ribbon.ServiceCaller;
import com.example.feign.NodeFeignService;
import com.example.feign.UserFeignService;
import com.example.ribbon.service.NoteTypeRibbonService;
import com.example.util.Results;
import com.example.util.constant.NodeUrlConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class NoteTypeRibbonServiceImpl implements NoteTypeRibbonService {

    @Autowired
    @Lazy
    ServiceCaller serviceCaller;

    @Autowired
    NodeFeignService nodeFeignService;

    @Autowired
    private UserFeignService userFeignService;

    @Override
    public JSONObject addNoteType(String typeName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("typeName", typeName);
        return serviceCaller.postByUserServiceName(NodeUrlConstant.NOTETYPE_SAVEORUPDATE,jsonObject,JSONObject.class);
    }

    @Override
    public JSONObject getNoteType(String nodeId, String id) {
        //获取数据节点
        DataNode dataNode =nodeFeignService.getDataNodeConfigById(nodeId);
        if(dataNode ==null){
            return Results.error("数据节点获取异常");
        }
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id",id);
        String url = UriComponentsBuilder
                .fromUriString(NodeUrlConstant.NOTETYPE_GETONE)
                .queryParams(params)
                .toUriString();
        return serviceCaller.get(dataNode.getNodeServerName(),url, JSONObject.class,new JSONObject());
    }

    @Override
    public JSONObject getNoteTypeListByUserId(String userId) {
        DataNode dataNode =userFeignService.findNodeByUserId(userId);
        if(dataNode ==null){
            return Results.error("数据节点获取异常");
        }
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("userId",userId);
        String url = UriComponentsBuilder
                .fromUriString(NodeUrlConstant.NOTETYPE_GETLIST_USERID)
                .queryParams(params)
                .toUriString();
        return serviceCaller.get(dataNode.getNodeServerName(),url,JSONObject.class,new JSONObject());
    }
}
